<template>
  <view class="page-container">
    <!-- 自定义Header -->
    <CustomHeader></CustomHeader>
    
    <!-- 页头 -->
    <view class="header-nav">
      <view class="back-btn" @click="goBack">
        <image class="back-icon" src="/static/icons/candidate/pre_page.png"></image>
      </view>
      <view class="header-title">面试邀请</view>
      <view class="header-right"></view>
    </view>

    <!-- 页面标题 -->
    <view class="page-title">
      <text class="title-text">邀请{{ candidateName }}</text>
    </view>

    <!-- 面试信息卡片 -->
    <view class="interview-card">
      <view class="card-title">面试信息</view>
      
      <!-- 职位信息 -->
      <view class="info-item" @click="selectPosition">
        <view class="info-label">
          <image class="info-icon" src="/static/icons/hr/position.png"></image>
          <text class="label-text">职位信息</text>
        </view>
        <view class="info-value">
          <text class="value-text" :class="{ 'placeholder': !selectedPosition }">
            {{ selectedPosition ? selectedPosition.jobName : '请选择职位' }}
          </text>
          <image class="arrow-icon" src="/static/icons/right-arrow-gray.png"></image>
        </view>
      </view>

      <!-- 联系电话 -->
      <view class="info-item">
        <view class="info-label">
          <image class="info-icon" src="/static/icons/hr/phone.png"></image>
          <text class="label-text">联系电话</text>
        </view>
        <view class="info-value">
          <input 
            class="value-input" 
            type="text" 
            v-model="contactPhone"
            placeholder="请输入联系电话"
            placeholder-class="input-placeholder"
          />
        </view>
      </view>

      <!-- 地址信息 -->
      <view class="info-item" @click="selectAddress">
        <view class="info-label">
          <image class="info-icon" src="/static/icons/hr/address.png"></image>
          <text class="label-text">面试地址</text>
        </view>
        <view class="info-value">
          <text class="value-text" :class="{ 'placeholder': !selectedAddress }">
            {{ selectedAddress ? selectedAddress.name : '请选择面试地址' }}
          </text>
          <image class="arrow-icon" src="/static/icons/right-arrow-gray.png"></image>
        </view>
      </view>

        <!-- 备注信息 -->
        <view class="info-item remark-item">
          <view class="info-label">
            <image class="info-icon" src="/static/icons/hr/remark.png"></image>
            <text class="label-text">备注信息</text>
          </view>
          <view class="info-value">
            <input 
              class="remark-input" 
              type="text"
              v-model="remark"
              placeholder="请输入备注信息（选填）"
              placeholder-class="input-placeholder"
              maxlength="200"
            />
          </view>
        </view>
      
    </view>

    <!-- 日历选择卡片 -->
    <view class="calendar-card">
      <view class="card-title">面试时间</view>
      
      <!-- 日期选择 -->
      <view class="date-section">
        <uni-calendar 
          ref="calendarRef"
          :insert="true"
          :lunar="false"
          :start-date="startDate"
          @change="onDateChange"
        />
      </view>
      
      <!-- 时间选择 -->
      <view class="time-section">
        <view class="time-label">面试时间</view>
        <view class="time-picker" @click="showTimePicker">
          <text class="time-text" :class="{ 'placeholder': !selectedTime }">
            {{ selectedTime || '请选择时间' }}
          </text>
          <image class="arrow-icon" src="/static/icons/right-arrow-gray.png"></image>
        </view>
      </view>
    </view>

    <!-- 固定底部按钮 -->
    <view class="fixed-bottom">
      <button 
        class="submit-btn" 
        @click="sendInvitation"
        :disabled="!canSubmit"
      >
        邀请面试
      </button>
    </view>

  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad, onShow, onHide } from '@dcloudio/uni-app'
import { useUserStore } from '@/stores/modules/user.js'
import CustomHeader from "@/components/CustomHeader.vue"
import { getJobDetailApi, getHrJobListApi } from '@/api/position.js'
import { sendInterviewInvitationApi } from '@/api/chat.js'

// Store
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

// Refs
const calendarRef = ref(null)

// 页面参数
const candidateName = ref('')
const candidateId = ref('')
const jobId = ref('')
const sessionId = ref('')

// 表单数据
const contactPhone = ref('')
const selectedPosition = ref(null)
const selectedAddress = ref(null)
const selectedDate = ref('')
const selectedTime = ref('')
const remark = ref('')

// 日历开始日期
const startDate = ref('')

// 计算属性：是否可以提交
const canSubmit = computed(() => {
  return selectedPosition.value && 
         contactPhone.value && 
         selectedAddress.value && 
         selectedDate.value &&
         selectedTime.value
})

// 页面加载
onLoad((options) => {
  
  // 获取页面参数
  candidateName.value = decodeURIComponent(options.candidateName || '候选人')
  candidateId.value = options.candidateId || ''
  jobId.value = options.jobId || ''
  sessionId.value = options.sessionId || ''
  
  // 设置日历开始日期为今天
  const today = new Date()
  startDate.value = formatDateForCalendar(today)
  
  // 默认选中今天
  selectedDate.value = formatDateForCalendar(today)
  
  // 从 userStore 获取联系电话
  if (userInfo.value && userInfo.value.phone) {
    contactPhone.value = userInfo.value.phone
  }
  
  // 如果有 jobId，获取职位详情
  if (jobId.value) {
    getJobDetail()
  }
  
  // 监听地址选择事件
  uni.$on('addressSelected', (address) => {
    selectedAddress.value = address
  })
})

// 页面显示时监听事件
onShow(() => {
  // 检查是否有选择的职位（从本地存储获取）
  const selectedPos = uni.getStorageSync('selectedPosition')
  if (selectedPos) {
    selectedPosition.value = selectedPos
    // 清除本地存储
    uni.removeStorageSync('selectedPosition')
  }
  
  // 检查是否有选择的地址（从本地存储获取）
  const selectedAddr = uni.getStorageSync('selectedAddress')
  if (selectedAddr) {
    selectedAddress.value = selectedAddr
    // 清除本地存储
    uni.removeStorageSync('selectedAddress')
  }
})

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 获取职位详情
const getJobDetail = async () => {
  try {
    const response = await getJobDetailApi(jobId.value)
    selectedPosition.value = response
  } catch (error) {
    console.error('获取职位详情失败:', error)
  }
}

// 选择职位
const selectPosition = () => {
  // 跳转到职位选择页面
  const params = {
    candidateName: encodeURIComponent(candidateName.value),
    candidateId: candidateId.value,
    sessionId: sessionId.value
  }
  
  const queryString = Object.keys(params)
    .map(key => `${key}=${params[key]}`)
    .join('&')
  
  
  uni.navigateTo({
    url: `/pages/company/interview/positionSelector?${queryString}`
  })
}

// 格式化薪资
const formatSalary = (job) => {
  if (job.beginSalary && job.endSalary) {
    return `${job.beginSalary}-${job.endSalary}K`
  }
  return '面议'
}

// 选择地址
const selectAddress = () => {
  uni.navigateTo({
    url: '/pages/company/interview/addressSelector'
  })
}

// 日历日期改变
const onDateChange = (e) => {
  if (e.fulldate) {
    selectedDate.value = e.fulldate
  }
}

// 显示时间选择器
const showTimePicker = () => {
  const timeSlots = [
    '09:00', '09:30', '10:00', '10:30', '11:00', '11:30',
    '14:00', '14:30', '15:00', '15:30', '16:00', '16:30',
    '17:00', '17:30', '18:00', '18:30', '19:00', '19:30'
  ]
  
  uni.showActionSheet({
    itemList: timeSlots,
    success: (res) => {
      selectedTime.value = timeSlots[res.tapIndex]
    }
  })
}

// 格式化日期为日历所需格式
const formatDateForCalendar = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 发送面试邀请消息
const sendInterviewMessage = async (interviewId) => {
  try {
    console.log('发送面试邀请消息，interviewId:', interviewId)
    
    // 构造消息数据
    const messageData = {
      sessionId: sessionId.value,
      senderId: userInfo.value.id,
      receiveId: candidateId.value,
      msgType: 14, // 面试邀请消息类型
      content: {
        interviewId: interviewId
      }
    }
    
    console.log('面试邀请消息数据:', messageData)
    
    // TODO: 实际项目中应该调用发送消息的API
    // 这里暂时模拟发送成功
    // await sendMessageApi(messageData)
    
    // 模拟发送成功
    console.log('面试邀请消息发送成功')
    
  } catch (error) {
    console.error('发送面试消息失败:', error)
  }
}

// 发送面试邀请
const sendInvitation = async () => {
  if (!canSubmit.value) {
    uni.showToast({
      title: '请完善面试信息',
      icon: 'none'
    })
    return
  }
  
  try {
    uni.showLoading({
      title: '发送中...'
    })
    
    // 格式化面试时间
    const interviewTime = `${selectedDate.value} ${selectedTime.value}`
    
    const data = {
      positionId: selectedPosition.value.id,
      positionName: selectedPosition.value.jobName,
      candidateId: candidateId.value,
      contactPhone: contactPhone.value,
      remarks: remark.value,
      interviewAddress: selectedAddress.value.name,
      interviewAddressLng: selectedAddress.value.longitude,
      interviewAddressLat: selectedAddress.value.latitude,
      interviewTime: interviewTime
    }
    
    
    const response = await sendInterviewInvitationApi(data)
    
    uni.hideLoading()
    
    // 发送面试邀请消息
    if (response && response.id) {
      await sendInterviewMessage(response.id)
    }
    
    uni.showToast({
      title: '邀请发送成功',
      icon: 'success',
      duration: 2000
    })
    
    // 延迟返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 2000)
    
  } catch (error) {
    uni.hideLoading()
    console.error('发送面试邀请失败:', error)
    uni.showToast({
      title: '发送失败，请重试',
      icon: 'none'
    })
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 180rpx;
}

.header-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

.header-right {
  width: 60rpx;
}

/* 页面标题 */
.page-title {
  background-color: #54cbc4;
  padding: 40rpx 30rpx;
  text-align: center;
}

.title-text {
  font-size: 48rpx;
  font-weight: bold;
  color: #ffffff;
}

/* 面试信息卡片 */
.interview-card {
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  display: flex;
  align-items: center;
  gap: 16rpx;
  flex-shrink: 0;
  width: 120rpx;
}

.info-icon {
  width: 40rpx;
  height: 40rpx;
  flex-shrink: 0;
}

.label-text {
  font-size: 30rpx;
  color: #666;
  white-space: nowrap;
}

.info-value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 16rpx;
  min-width: 0;
}

.value-text {
  font-size: 30rpx;
  color: #333;
  text-align: right;
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.value-text.placeholder {
  color: #999;
}

.value-input {
  font-size: 30rpx;
  color: #333;
  text-align: right;
  flex: 1;
  min-width: 0;
  width: 100%;
  box-sizing: border-box;
}

.input-placeholder {
  color: #999;
}

.arrow-icon {
  width: 24rpx;
  height: 24rpx;
}

/* 备注样式 */
.remark-item {
  align-items: flex-start;
  padding-top: 30rpx;
}

.remark-item .info-label {
  margin-top: 10rpx;
  width: 120rpx;
  flex-shrink: 0;
}

.remark-input {
  font-size: 30rpx;
  color: #333;
  text-align: right;
  flex: 1;
  min-width: 0;
  width: 100%;
  box-sizing: border-box;
}

/* 日历卡片 */
.calendar-card {
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin: 0 30rpx 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.date-section {
  margin-bottom: 30rpx;
}

.time-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  border-top: 1rpx solid #f0f0f0;
  width: 100%;
  box-sizing: border-box;
}

.time-label {
  font-size: 30rpx;
  color: #666;
  font-weight: 500;
  flex-shrink: 0;
  width: 120rpx;
}

.time-picker {
  display: flex;
  align-items: center;
  gap: 16rpx;
  flex: 1;
  justify-content: flex-end;
  min-width: 0;
}

.time-text {
  font-size: 30rpx;
  color: #333;
  flex: 1;
  text-align: right;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.time-text.placeholder {
  color: #999;
}

/* 固定底部按钮 */
.fixed-bottom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background-color: #ffffff;
  border-top: 1rpx solid #f0f0f0;
  z-index: 100;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background-color: #54cbc4;
  color: #ffffff;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 44rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.submit-btn[disabled] {
  background-color: #cccccc;
  color: #ffffff;
}

</style>